﻿using FastMvc.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text;

namespace FastMvc.Filters
{
    public class DtoValidationFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                // 验证结果的返回格式化
                var result = new BaseResult()
                {
                    code = 8,
                    success = false,
                    message = "输入字段验证错误！",
                    Errors = new List<ErrorMsg>()
                };
                foreach (var ekey in context.ModelState.Keys)
                {
                    var err = context.ModelState[ekey];
                    result.Errors.Add(new ErrorMsg() { parameter = ekey, message = err.Errors[0].ErrorMessage });
                }

                context.Result = new ContentResult() { ContentType = "application/json", Content = Newtonsoft.Json.JsonConvert.SerializeObject(result), StatusCode = 200 };
            }
        }
    }
}
